package com.njlime.cms.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.entities.Information;
import com.njlime.cms.sdk.weibo4j.util.WeiboConfig;
import com.njlime.cms.service.sys.InformationService;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.BusinessException;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.sdk.wechat.WeChatUtil;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.UnitService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 头条发布
 * Created by Dean on 2017/10/14.
 */
@Controller
@RequestMapping(value = "/toutiao")
public class TouTiaoController extends BaseController {
    @Resource
    private InformationService informationService;
    @Resource
    private UnitService unitService;

    public static String TouTiaoAuthorizeCode = "ttAuthorizeCode";
    public static String TouTiaoToken = "ttToken";
    public static String TouTiaoUserName = "ttUserName";

    @RequestMapping(value = "/authorizeCallBack")
    public ModelAndView authorizeCallBack(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView info = new ModelAndView("/sys/content/information/loginSuccess");
        info.addObject("type","toutiao");
        System.out.println("authorizeCallBack------------------->>>>>>>start");
        String access_token = "";
        try {
            Object error_code = request.getParameter("error_code");
            if (error_code == null) {
                //头条
                String authorizeCode = request.getParameter("code").toString();
                request.getSession().setAttribute(TouTiaoAuthorizeCode, authorizeCode);
                //回调参数
                String state = request.getParameter("state").toString();
                System.out.println("头条授权成功，授权码：" + authorizeCode);
                String url = "https://open.snssdk.com/auth/token/";
                UnitWxConfig config = unitService.getWxConfig(unitService.getRootUnit(Integer.valueOf(state)));
                String outPutString = "code=" + authorizeCode + "&client_key=" + config.getTt_key() + "&client_secret=" + config.getTt_secret() + "&grant_type=authorize_code";

                JSONObject jsonObject = WeChatUtil.httpRequest(url + "?" + outPutString, "POST", "");
                System.out.println("token:" + jsonObject.toJSONString());
                System.out.println("publicByTouTiao------------------->>>>>>>start");
                try {
                    access_token = jsonObject.getJSONObject("data").getString("access_token");
                    request.getSession().setAttribute(TouTiaoToken, access_token);
                    String touTiaoUserName = jsonObject.getJSONObject("data").getString("screen_name");
                    request.getSession().setAttribute(TouTiaoUserName, touTiaoUserName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("publicByTouTiao------------------->>>>>>>end");
            } else {
                System.out.println("头条授权失败" + error_code);
                info.setViewName("/sys/content/information/loginFail");
                return info;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("头条授权失败");
            info.setViewName("/sys/content/information/loginFail");
            return info;
        }

        System.out.println("authorizeCallBack------------------->>>>>>>end");
        return info;
    }

    /**
     * 通过头条发布
     *
     * @param title       标题
     * @param content     内容
     * @param abstractS   摘要
     * @param save        保存方式 0 存草稿，1 发布
     * @param article_tag 文章分类  https://open.mp.toutiao.com/index.html#/resource?_k=trnpu4
     * @return
     */
    private boolean publicByTouTiao(String access_token, String title, String content, String abstractS, String save, int article_tag) throws Exception{
        String url = "https://mp.toutiao.com/open/new_article_post/";
        JSONObject reqData = new JSONObject();
        reqData.put("title", title);
        reqData.put("content", content);
        reqData.put("abstract", abstractS);
        reqData.put("save", save);
        reqData.put("article_tag", article_tag);
        Unit rootUnit = getLoginUser().getRootUnit();
        UnitWxConfig config = unitService.getWxConfig(rootUnit.getId());
        JSONObject jsonObject = WeChatUtil.httpRequest(url + "?" + "access_token=" + access_token + "&client_key=" + config.getTt_key(), "POST", "title=" + title + "&content=" + content + "&abstract=" + abstractS + "&save=" + save + "&article_tag=" + article_tag);
        if("error".equals(jsonObject.getString("message"))){
            throw new BusinessException(jsonObject.getString("data"));
        }
        System.out.println("new_article_post:" + jsonObject.toJSONString());
        return true;
    }

    /**
     * 文章内容通过头条号发布到素材库
     *
     * @param id      文章id
     * @param request 请求
     * @return
     */
    @RequestMapping(value = "informationTouTiao")
    @ResponseBody
    public String informationTouTiao(int id, HttpServletRequest request) {
        try {
            Information information = informationService.findOne(id);
            String access_token = request.getSession().getAttribute(TouTiaoToken).toString();
            publicByTouTiao(access_token, information.getTitle(), information.getContent(), information.getAbstract_info(), "0", 12);
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,e.getMessage());
        }
        return toJsonSuccessData();
    }

    @RequestMapping(value = "getTouTiaoUser")
    @ResponseBody
    public String getTouTiaoUser(HttpServletRequest request, HttpServletResponse response) {
        Object userName = request.getSession().getAttribute(TouTiaoUserName);
        if (userName == null) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"查询用户失败");
        }
        return toJsonSuccessData(userName);
    }

    @RequestMapping(value = "ttCheck")
    @ResponseBody
    public String ttCheck(HttpServletRequest request, HttpServletResponse response) {
        Integer unit_id = getLoginUser().getUnit_id();
        UnitWxConfig config = unitService.getWxConfig(unit_id);
        if(config == null && config.getTt_key() == null){
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请先在账户管理中绑定头条号");
        }
        Map<String,Object> result = new HashMap<>();
        result.put("key", config.getTt_key());
        result.put("unit", unit_id);
        result.put("uri", WeiboConfig.getValue("tt_redirect_URI"));
        return toJsonSuccessData(result);
    }

}